const axios = require('axios');
const jwt = require('jsonwebtoken');

// Base URL for the API
const BASE_URL = 'http://localhost:3003';

// Generate a valid JWT token for testing
const JWT_SECRET = 'financeapp_jwt_secret'; // This should match the secret in your .env file
const TEST_USER_ID = 1;

// Generate a valid token
const TEST_JWT_TOKEN = jwt.sign({ userId: TEST_USER_ID }, JWT_SECRET, { expiresIn: '24h' });

async function testReporting() {
  try {
    console.log('Testing Report Generation API...');
    
    // 1. Generate a summary report
    console.log('\n1. Generating summary report...');
    try {
      const response = await axios.post(`${BASE_URL}/api/reports/generate`, {}, {
        headers: {
          'Authorization': `Bearer ${TEST_JWT_TOKEN}`
        },
        params: {
          type: 'summary',
          start_date: '2025-01-01',
          end_date: '2025-01-31'
        }
      });
      
      console.log('✓ Summary report generated successfully:');
      console.log(`  Report ID: ${response.data.report.id}`);
      console.log(`  Report Type: ${response.data.report.type}`);
      console.log(`  Generated At: ${response.data.report.generated_at}`);
      
      if (response.data.report.data) {
        console.log('  Report Data:');
        console.log(`    Period: ${response.data.report.data.period?.start_date} to ${response.data.report.data.period?.end_date}`);
        console.log(`    Total Income: ${response.data.report.data.summary?.total_income}`);
        console.log(`    Total Expense: ${response.data.report.data.summary?.total_expense}`);
        console.log(`    Net Balance: ${response.data.report.data.summary?.net_balance}`);
      }
    } catch (error) {
      console.error('✗ Failed to generate summary report:', error.response?.data || error.message);
    }
    
    // 2. Generate a category report
    console.log('\n2. Generating category report...');
    try {
      const response = await axios.post(`${BASE_URL}/api/reports/generate`, {}, {
        headers: {
          'Authorization': `Bearer ${TEST_JWT_TOKEN}`
        },
        params: {
          type: 'category',
          start_date: '2025-01-01',
          end_date: '2025-01-31'
        }
      });
      
      console.log('✓ Category report generated successfully:');
      console.log(`  Report ID: ${response.data.report.id}`);
      console.log(`  Report Type: ${response.data.report.type}`);
      
      if (response.data.report.data) {
        console.log('  Report Data:');
        console.log(`    Income Categories: ${response.data.report.data.income_by_category?.length || 0}`);
        console.log(`    Expense Categories: ${response.data.report.data.expenses_by_category?.length || 0}`);
      }
    } catch (error) {
      console.error('✗ Failed to generate category report:', error.response?.data || error.message);
    }
    
    // 3. Generate a trend report
    console.log('\n3. Generating trend report...');
    try {
      const response = await axios.post(`${BASE_URL}/api/reports/generate`, {}, {
        headers: {
          'Authorization': `Bearer ${TEST_JWT_TOKEN}`
        },
        params: {
          type: 'trend',
          start_date: '2025-01-01',
          end_date: '2025-01-31'
        }
      });
      
      console.log('✓ Trend report generated successfully:');
      console.log(`  Report ID: ${response.data.report.id}`);
      console.log(`  Report Type: ${response.data.report.type}`);
      
      if (response.data.report.data) {
        console.log('  Report Data:');
        console.log(`    Daily Trends: ${response.data.report.data.daily_trend?.length || 0} days`);
        console.log(`    Monthly Summary: ${response.data.report.data.monthly_summary?.length || 0} months`);
      }
    } catch (error) {
      console.error('✗ Failed to generate trend report:', error.response?.data || error.message);
    }
    
    // 4. Get all reports
    console.log('\n4. Retrieving all reports...');
    try {
      const response = await axios.get(`${BASE_URL}/api/reports`, {
        headers: {
          'Authorization': `Bearer ${TEST_JWT_TOKEN}`
        }
      });
      
      console.log(`✓ Retrieved ${response.data.reports.length} reports:`);
      response.data.reports.forEach(report => {
        console.log(`  - ID: ${report.id}, Type: ${report.type}, Generated: ${report.generated_at}`);
      });
    } catch (error) {
      console.error('✗ Failed to retrieve reports:', error.response?.data || error.message);
    }
    
    console.log('\n✓ All reporting tests completed successfully!');
  } catch (error) {
    console.error('Test failed:', error.message);
  }
}

// Run the test
testReporting();